from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
import jwt
from jwt import exceptions

from lenovo import settings


class JwtAuthorizationAuthentication(BaseAuthentication):
    def authenticate(self, request):
        auth_header = request.META.get('HTTP_AUTHORIZATION')
        print("Request Headers:")
        for key, value in request.META.items():
            if key.startswith('HTTP_'):
                print(f"{key}: {value}")

        if not auth_header:
            raise AuthenticationFailed("未提供认证信息")

        try:
            # Remove 'Bearer ' prefix and decode the token.
            if auth_header.startswith('Bearer '):
                access_token = auth_header[7:]
                print(f"Access Token: {access_token}")
            else:
                raise AuthenticationFailed({'code': 1004, "message": "不正确的认证头前缀"})

            payload = jwt.decode(access_token, settings.SECRET_KEY, algorithms=['HS256'])
            return (payload, access_token)

        except exceptions.ExpiredSignatureError:
            raise AuthenticationFailed({'code': 1001, "message": "token已失效"})
        except jwt.DecodeError:
            raise AuthenticationFailed({'code': 1002, "message": "token认证失败"})
        except jwt.InvalidTokenError:
            raise AuthenticationFailed({'code': 1003, "message": "非法的token"})